use eframe::egui::{self, Color32, RichText};

fn main() -> Result<(), eframe::Error> {
    let options = eframe::NativeOptions {
        viewport: egui::viewport::ViewportBuilder::default()
            .with_inner_size([1000.0, 600.0])
            .with_title("SDMPConfigTools"),
        ..Default::default()
    };

    eframe::run_native(
        "SDMPConfigTools",
        options,
        Box::new(|_cc| Ok(Box::new(ConfigApp::default()))),
    )
}

#[derive(Default)]
struct ConfigApp {
    device_type: usize,
    devices: Vec<DeviceInfo>,
}

#[derive(Clone)]
struct DeviceInfo {
    id: String,
    model: String,
    version: String,
    version_id: String,
    ip: String,
}

impl Default for DeviceInfo {
    fn default() -> Self {
        Self {
            id: "001".to_string(),
            model: "Gateway".to_string(),
            version: "v1.0".to_string(),
            version_id: "build-001".to_string(),
            ip: "192.168.0.1".to_string(),
        }
    }
}

impl eframe::App for ConfigApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        ctx.set_visuals(egui::Visuals::dark());

        // Top icon buttons + title
        egui::TopBottomPanel::top("top_toolbar").show(ctx, |ui| {
            ui.horizontal_wrapped(|ui| {
                ui.set_height(100.0);
                ui.add_space(4.0);

                ui.add_sized([100.0, 100.0], egui::Button::new("⚙ Network"));
                ui.add_sized([100.0, 100.0], egui::Button::new("🌐 Online"));
                ui.add_sized([100.0, 100.0], egui::Button::new("👤 Test"));

                ui.add_space(20.0);
                ui.label(RichText::new("SDMPConfigTools").heading().strong().size(22.0));
            });
        });

        // Filter row
        egui::TopBottomPanel::top("filter_bar").show(ctx, |ui| {
            ui.horizontal(|ui| {
                let types = ["All Devices", "Gateway", "Sensor"];
                egui::ComboBox::from_label("Device Type")
                    .selected_text(types[self.device_type])
                    .width(160.0)
                    .show_ui(ui, |ui| {
                        for (i, name) in types.iter().enumerate() {
                            ui.selectable_value(&mut self.device_type, i, *name);
                        }
                    });

                if ui.add_sized([80.0, 28.0], egui::Button::new("Search")).clicked() {
                    self.devices = mock_devices();
                }
                if ui.add_sized([80.0, 28.0], egui::Button::new("Clear")).clicked() {
                    self.devices.clear();
                }
            });
        });

        // Main content area
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.columns(2, |cols| {
                // Left: Table
                egui::ScrollArea::vertical().show(&mut cols[0], |ui| {
                    ui.separator();
                    egui::Grid::new("device_table")
                        .striped(true)
                        .min_col_width(90.0)
                        .spacing([12.0, 8.0])
                        .show(ui, |ui| {
                            let header_text = |text: &str| {
                                RichText::new(text).strong().size(14.0).color(Color32::WHITE)
                            };

                            ui.label(header_text("ID"));
                            ui.label(header_text("Model"));
                            ui.label(header_text("Version"));
                            ui.label(header_text("Version ID"));
                            ui.label(header_text("IP Address"));
                            ui.end_row();

                            for d in &self.devices {
                                ui.label(&d.id);
                                ui.label(&d.model);
                                ui.label(&d.version);
                                ui.label(&d.version_id);
                                ui.label(&d.ip);
                                ui.end_row();
                            }
                        });
                });

                // Right: Empty Detail Panel
                cols[1].vertical_centered(|ui| {
                    ui.add_space(20.0);
                    ui.label("📋 Device Detail Panel (empty)");
                });
            });
        });
    }
}

fn mock_devices() -> Vec<DeviceInfo> {
    vec![
        DeviceInfo {
            id: "001".to_string(),
            model: "Gateway".to_string(),
            version: "v1.2.3".to_string(),
            version_id: "GATEWAY-001".to_string(),
            ip: "192.168.0.101".to_string(),
        },
        DeviceInfo {
            id: "002".to_string(),
            model: "Sensor".to_string(),
            version: "v1.1.0".to_string(),
            version_id: "SENSOR-001".to_string(),
            ip: "192.168.0.102".to_string(),
        },
    ]
}
